﻿using System.IO.Compression;

namespace CompressDemo;

internal class SystemIOCompressionDemo
{
    private readonly string _fileName = "原生.zip";
    private readonly string _startPath = AppInfo.SourceDirectory; // files 目录
    private readonly string _desPath = AppInfo.TargetDirectory; // target 目录
    private readonly string _gzipFile = Path.Combine(AppInfo.TargetDirectory, "gzipfile.gz");
    private string DesFullName => Path.Combine(_desPath, _fileName);

    /// <summary>
    /// 压缩目录
    /// </summary>
    /// <returns></returns>
    public Task CompressDirectory()
    {
        if (File.Exists(DesFullName)) File.Delete(DesFullName);

        // 将 files 目录压缩 默认的参数
        ZipFile.CreateFromDirectory(_startPath, DesFullName, CompressionLevel.Optimal, includeBaseDirectory: false);
        return Task.CompletedTask;
    }

    public Task CompressFile()
    {
        if (File.Exists(DesFullName)) File.Delete(DesFullName);

        using (ZipArchive archive = ZipFile.Open(DesFullName, ZipArchiveMode.Create))
        {
            var fileName1 = Path.Combine(_startPath, "268-c1.bin");
            archive.CreateEntryFromFile(fileName1, Path.GetFileName(fileName1));

            var fileName2 = Path.Combine(_startPath, "U8中文.txt");
            archive.CreateEntryFromFile(fileName2, "u8/" + Path.GetFileName(fileName2));
        }

        return Task.CompletedTask;
    }
    public Task Decompress()
    {
        ZipFile.ExtractToDirectory(DesFullName, Path.Combine(_desPath, "新建文件夹"));
        return Task.CompletedTask;
    }
    public Task CompressGZIP()
    {

        // 获取要压缩的文件流
        using FileStream originalFileStream = File.Open(Path.Combine(AppInfo.SourceDirectory, "268-c1.bin"), FileMode.Open);

        // 创建另一个文件流
        using FileStream compressedFileStream = File.Create(_gzipFile);

        using var compressor = new GZipStream(compressedFileStream, CompressionMode.Compress);
        originalFileStream.CopyTo(compressor);
        return Task.CompletedTask;
    }
}
